/**
 * 通用 CRUD 工具函数
 * 用于简化前端增删改查操作
 */

/**
 * 获取列表
 * @param {String} type - 类型：user/role/permission/menu
 * @param {Object} options - 查询选项
 * @returns {Promise}
 */
export function getList(type, options = {}) {
	const vk = uni.vk;
	const {
		pageIndex = 1,
		pageSize = 20,
		keyword = '',
		orderBy,
		orderType = 'desc',
		where = {}
	} = options;
	
	return vk.callFunction({
		url: 'admin/system/base/getList',
		data: {
			type,
			pageIndex,
			pageSize,
			keyword,
			orderBy,
			orderType,
			where
		}
	});
}

/**
 * 新增
 * @param {String} type - 类型：user/role/permission/menu
 * @param {Object} formData - 表单数据
 * @returns {Promise}
 */
export function add(type, formData) {
	const vk = uni.vk;
	return vk.callFunction({
		url: 'admin/system/base/add',
		data: {
			type,
			...formData
		}
	});
}

/**
 * 更新
 * @param {String} type - 类型：user/role/permission/menu
 * @param {String} _id - ID
 * @param {Object} formData - 表单数据
 * @returns {Promise}
 */
export function update(type, _id, formData) {
	const vk = uni.vk;
	return vk.callFunction({
		url: 'admin/system/base/update',
		data: {
			type,
			_id,
			...formData
		}
	});
}

/**
 * 删除
 * @param {String} type - 类型：user/role/permission/menu
 * @param {String|Array} ids - ID 或 ID 数组
 * @returns {Promise}
 */
export function remove(type, ids) {
	const vk = uni.vk;
	const data = {
		type
	};
	
	if (Array.isArray(ids)) {
		data.ids = ids;
	} else {
		data._id = ids;
	}
	
	return vk.callFunction({
		url: 'admin/system/base/delete',
		data
	});
}

/**
 * 批量删除
 * @param {String} type - 类型：user/role/permission/menu
 * @param {Array} ids - ID 数组
 * @returns {Promise}
 */
export function batchDelete(type, ids) {
	return remove(type, ids);
}

/**
 * 获取详情
 * @param {String} type - 类型：user/role/permission/menu
 * @param {String} _id - ID
 * @returns {Promise}
 */
export function getDetail(type, _id) {
	const vk = uni.vk;
	return vk.callFunction({
		url: 'admin/system/base/getDetail',
		data: {
			type,
			_id
		}
	});
}

/**
 * 统一的错误处理
 * @param {Object} res - 响应结果
 * @param {Function} successCallback - 成功回调
 * @param {Function} failCallback - 失败回调
 */
export function handleResponse(res, successCallback, failCallback) {
	const vk = uni.vk;
	
	if (res.code === 0) {
		if (successCallback) {
			successCallback(res.data);
		} else {
			vk.toast(res.msg || '操作成功');
		}
		return true;
	} else {
		const msg = res.msg || '操作失败';
		vk.toast(msg);
		if (failCallback) {
			failCallback(res);
		}
		return false;
	}
}

